package com.lgqz.himalayafm.fragment;


import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lgqz.himalayafm.R;
import com.lgqz.himalayafm.adapter.DiscoverNoveltyAdapter;
import com.lgqz.himalayafm.adapter.FocusImageAdapter;
import com.lgqz.himalayafm.adapter.RecommendAdapter;
import com.lgqz.himalayafm.bean.CataIndexBannerEntity;
import com.lgqz.himalayafm.bean.EditorRecommendAlbums;
import com.lgqz.himalayafm.bean.Entity;
import com.lgqz.himalayafm.bean.Guess;
import com.lgqz.himalayafm.bean.ItemEntity;
import com.lgqz.himalayafm.bean.RecommendList;
import com.lgqz.himalayafm.bean.RecyclerRecommend;
import com.lgqz.himalayafm.http.HttpService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class RecommendFragment extends Fragment implements ViewPager.OnPageChangeListener, SwipeRefreshLayout
        .OnRefreshListener, AppBarLayout.OnOffsetChangedListener {


    private ViewPager mFocusViewPager;
    private int currentPosition;
    private List<SimpleDraweeView> mViewList;
    private LinearLayout mFocusDotLayout;
    private ViewPager mDiscoveryViewPager;
    private LinearLayout mDiscoveryDotLayout;
    private List<RecyclerRecommend> mRecommendList;
    private RecommendAdapter mRecommendAdapter;
    private boolean isFirstFinish;
    private boolean isSecondFinish;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                mFocusViewPager.setCurrentItem(++currentPosition);
            }
        }
    };
    private SwipeRefreshLayout mRefreshLayout;
    private HttpService mService;
    private HttpService mService2;
    private FocusImageAdapter mFocusImageAdapter;

    public RecommendFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/mobile/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        mService = retrofit.create(HttpService.class);
        mRecommendList = new ArrayList<>();
        getFirstJSONData(mService);
        getSecondJSONData(mService);

        Retrofit retrofit2 = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        mService2 = retrofit2.create(HttpService.class);
        getThirdJSONData(mService2);
    }

    private void getThirdJSONData(HttpService service) {
        service.getCataIndexBannerData("android", "find_banner", "wifi", 0, "4.3.98").enqueue(new Callback<CataIndexBannerEntity>() {
            @Override
            public void onResponse(Call<CataIndexBannerEntity> call, Response<CataIndexBannerEntity> response) {
                List<CataIndexBannerEntity.CataIndexBannerData> data = response.body().getData();
                mRecommendAdapter.getAdvertisementData(data);
            }

            @Override
            public void onFailure(Call<CataIndexBannerEntity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getSecondJSONData(HttpService service) {
        //    http://mobile.ximalaya.com/mobile/discovery/v1/recommend/hotAndGuess?device=android
        service.getRecommend("discovery", "v1", "recommend", "hotAndGuess", "android").enqueue(new Callback<Entity>() {
            @Override
            public void onResponse(Call<Entity> call, Response<Entity> response) {
                Log.d("Debug", "onResponse: " + response.isSuccessful());
                List<RecommendList> recommendList = response.body().getHotRecommends().getList();
                Guess guess = response.body().getGuess();
                RecyclerRecommend guessRecyclerRecommend = new RecyclerRecommend();
                guessRecyclerRecommend.setTitle(guess.getTitle());
                guessRecyclerRecommend.setList(guess.getList());
                mRecommendList.add(guessRecyclerRecommend);

                for (int i = 0; i < recommendList.size(); i++) {
                    RecommendList recommend = recommendList.get(i);
                    RecyclerRecommend recyclerRecommend = new RecyclerRecommend();
                    recyclerRecommend.setTitle(recommend.getTitle());
                    recyclerRecommend.setCategoryId(recommend.getCategoryId());
                    recyclerRecommend.setCategoryType(recommend.getCategoryType());
                    recyclerRecommend.setList(recommend.getList());
                    mRecommendList.add(recyclerRecommend);
                }
                isSecondFinish = true;
                if (isFirstFinish) {
                    mRecommendAdapter.addAll(mRecommendList);
                    mRecommendAdapter.addFooterView(LayoutInflater.from(getContext()).inflate(R.layout
                            .item_advertisement, null));
                    if (mRefreshLayout.isRefreshing()) {
                        mRefreshLayout.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onFailure(Call<Entity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getFirstJSONData(HttpService service) {
        service.getData("discovery", "v3", "recommends", "and-a1", "android", true, true, 2, "4.3.98").enqueue(new Callback<Entity>() {
            @Override
            public void onResponse(Call<Entity> call, Response<Entity> response) {
                aboutFocus(response);

                aboutNovelty(response);

                EditorRecommendAlbums editorRecommendAlbums = response.body().getEditorRecommendAlbums();
                RecyclerRecommend editorRecyclerRecommend = new RecyclerRecommend();
                editorRecyclerRecommend.setTitle(editorRecommendAlbums.getTitle());
                editorRecyclerRecommend.setList(editorRecommendAlbums.getList());
                mRecommendList.add(editorRecyclerRecommend);
                isFirstFinish = true;
                if (isSecondFinish) {
                    mRecommendAdapter.addAll(mRecommendList);
                    mRecommendAdapter.addFooterView(LayoutInflater.from(getContext()).inflate(R.layout
                            .item_advertisement, null));
                    if (mRefreshLayout.isRefreshing()) {
                        mRefreshLayout.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onFailure(Call<Entity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recommend, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl_recommend);
        mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_green_light,
                android.R.color.holo_red_light, android.R.color.holo_purple);
        mRefreshLayout.measure(0, 0);
        mRefreshLayout.setRefreshing(true);
        mRefreshLayout.setOnRefreshListener(this);

        AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.ab_recommend);
        appBarLayout.addOnOffsetChangedListener(this);

        mFocusViewPager = (ViewPager) view.findViewById(R.id.focus_container_discover);
        mFocusDotLayout = (LinearLayout) view.findViewById(R.id.focus_dot_discover);

        mDiscoveryViewPager = (ViewPager) view.findViewById(R.id.discovery_container_discover);
        mDiscoveryDotLayout = (LinearLayout) view.findViewById(R.id.discovery_dot_discover);

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recommend_recycler_discover);
        mRecommendAdapter = new RecommendAdapter(getContext());
        recyclerView.setAdapter(mRecommendAdapter);

        Timer timer = new Timer();
        MyTimerTask myTimerTask = new MyTimerTask();
        timer.schedule(myTimerTask, 0, 5000);
    }

    private void aboutNovelty(Response<Entity> response) {
        List<DiscoverNoveltyFragment> discoverNoveltyFragments = getDiscoverNoveltyFragmentList(response);
        for (int i = 0; i < discoverNoveltyFragments.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(R.drawable.novelty_dot_selector);
            mDiscoveryDotLayout.addView(imageView);
        }
        DiscoverNoveltyAdapter noveltyAdapter = new DiscoverNoveltyAdapter(getFragmentManager(),
                discoverNoveltyFragments);
        mDiscoveryViewPager.setAdapter(noveltyAdapter);
        mDiscoveryViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < mDiscoveryDotLayout.getChildCount(); i++) {
                    if (i == position) {
                        mDiscoveryDotLayout.getChildAt(i).setSelected(true);
                    } else {
                        mDiscoveryDotLayout.getChildAt(i).setSelected(false);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @NonNull
    private List<DiscoverNoveltyFragment> getDiscoverNoveltyFragmentList(Response<Entity> response) {
        List<ItemEntity> discoverNoveltyList = response.body().getDiscoveryColumns().getList();
        ArrayList<ItemEntity> discoverNoveltyList_first = new ArrayList<>();
        ArrayList<ItemEntity> discoverNoveltyList_second = new ArrayList<>();
        int count = 0;
        for (ItemEntity itemEntity : discoverNoveltyList) {
            if (count < discoverNoveltyList.size() / 2) {
                discoverNoveltyList_first.add(itemEntity);
            } else {
                discoverNoveltyList_second.add(itemEntity);
            }
            count++;
        }
        List<DiscoverNoveltyFragment> discoverNoveltyFragments = new LinkedList<>();
        for (int i = 0; i < discoverNoveltyList.size() / 4; i++) {
            DiscoverNoveltyFragment fragment = null;
            switch (i) {
                case 0:
                    fragment = DiscoverNoveltyFragment.newInstance(discoverNoveltyList_first);
                    break;
                case 1:
                    fragment = DiscoverNoveltyFragment.newInstance
                            (discoverNoveltyList_second);
                    break;
            }
            discoverNoveltyFragments.add(fragment);
        }
        return discoverNoveltyFragments;
    }

    private void aboutFocus(Response<Entity> response) {
        List<ItemEntity> focusImageList = response.body().getFocusImages().getList();
        for (int i = 0; i < focusImageList.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(R.drawable.dot_selector);
            mFocusDotLayout.addView(imageView);
        }

        List<String> picUrlList = new LinkedList<>();
        picUrlList.add(focusImageList.get(focusImageList.size() - 1).getPic());
        for (int i = 0; i < focusImageList.size(); i++) {
            picUrlList.add(focusImageList.get(i).getPic());
        }
        picUrlList.add(focusImageList.get(0).getPic());

        mViewList = new LinkedList<>();
        for (int i = 0; i < picUrlList.size(); i++) {
            SimpleDraweeView draweeView = new SimpleDraweeView(getContext());
            GenericDraweeHierarchy hierarchy = draweeView.getHierarchy();
            hierarchy.setPlaceholderImage(R.drawable.focus_img_nonet);
            hierarchy.setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
            draweeView.setImageURI(Uri.parse(picUrlList.get(i)));
            mViewList.add(draweeView);
        }

        mFocusImageAdapter = new FocusImageAdapter(mViewList);
        mFocusViewPager.setAdapter(mFocusImageAdapter);
        mFocusViewPager.setCurrentItem(1, false);
        mFocusDotLayout.getChildAt(0).setSelected(true);
        mFocusViewPager.addOnPageChangeListener(this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentPosition = position;
        for (int i = 0; i < mFocusDotLayout.getChildCount(); i++) {
            if (i == position - 1) {
                mFocusDotLayout.getChildAt(i).setSelected(true);
            } else {
                mFocusDotLayout.getChildAt(i).setSelected(false);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (currentPosition == 0) {
                    mFocusViewPager.setCurrentItem(mViewList.size() - 2, false);
                } else if (currentPosition == mViewList.size() - 1) {
                    mFocusViewPager.setCurrentItem(1, false);
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mFocusViewPager.removeOnPageChangeListener(this);
    }

    @Override
    public void onRefresh() {
        mRefreshLayout.setRefreshing(false);
//        mRecommendList.clear();
//        mViewList.clear();
//        isFirstFinish = false;
//        isSecondFinish = false;
//        getFirstJSONData(mService);
//        getSecondJSONData(mService);
//        mFocusImageAdapter.notifyDataSetChanged();
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset >= 0) {
            mRefreshLayout.setEnabled(true);
        } else {
            mRefreshLayout.setEnabled(false);
        }
    }

    class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(1);
        }
    }
}
